<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>图片配置loading状态和失败状态</title>
    <style>
        img{
            width: 300px;
            margin: 20px;
        }
    </style>
    <script src="http://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js"></script>
    <script>
        //配置loading中的图片
        let imgLoading = "img/img-loading.gif";
        //配置加载失败的图片
        let imgFail = "img/img-no.jpg";
        //提前加载需要的图片资源
        new Image().src = imgLoading;
        new Image().src = imgFail;

        /**
         * 处理图片方法
         * @param obj 处理的图片元素
         */
        function handleImg(obj){
            obj.onerror = function () {
                obj.src = imgFail
            };
            setTimeout(function() {
                if (!obj.complete) {
                    //新建一个临时的图片元素
                    let temp = new Image();
                    //原图片路径赋值给临时图片元素
                    temp.src = obj.getAttribute("src");
                    //原图片改成loading图片
                    obj.setAttribute("src", imgLoading);
                    //临时图片元素设置加载完成回调函数
                    temp.onload = function () {
                        obj.src = temp.src
                    };
                }
            },1000);
        }

        //dom结构加载完后对所有img节点进行loading处理
        $(document).ready(function(){
            let imgList = document.getElementsByTagName('img');
            for (let img of imgList) {
                handleImg(img)
            }
        });
    </script>
</head>
<body>

<div>
    <img src="http://www.3kkg.com/image/63bf7a817b2d6de2573e7701e24c56ba.jpg" />
    <img src="http://www.3kkg.com/image/118a970e71455bb45fb14df9153616b0.png" />
    <img src="#" />
</div>

</body>
</html>